package com.qwc.blog.common.filter;

import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.text.CharSequenceUtil;
import com.qwc.blog.common.constant.ConfigConstant;
import com.qwc.blog.common.constant.ResponseConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author qiuwencong
 * @Date 2022/2/8 13:46
 * @Package com.qwc.blog.common.filter
 * @Description
 */
@Slf4j
@WebFilter(urlPatterns = {"/admin/*"})
public class AuthenticateFilter extends OncePerRequestFilter {

    @Autowired
    private TimedCache<String, String> cache;

    private static final String AUTHORIZATION = "Authorization";
    private static final String BEARER = "Bearer ";
    private static final String OPTIONS = "OPTIONS";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String authorization = CharSequenceUtil.removePrefix(request.getHeader(AUTHORIZATION), BEARER);
        if (OPTIONS.equalsIgnoreCase(request.getMethod())) {
            filterChain.doFilter(request, response);
        } else if (CharSequenceUtil.isNotBlank(authorization) && authorization.equals(cache.get(ConfigConstant.TOKEN))) {
            filterChain.doFilter(request, response);
        } else {
            cache.remove(ConfigConstant.TOKEN);
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, ResponseConstant.UNAUTHORIZED);
        }
    }

}
